package com.xiaoxin.service;

import cn.hutool.core.collection.CollUtil;
import com.xiaoxin.commons.utils.Constants;
import com.xiaoxin.dubbo.api.CommentApi;
import com.xiaoxin.dubbo.api.UserInfoApi;
import com.xiaoxin.exception.BusinessException;
import com.xiaoxin.interceptor.UserHolder;
import com.xiaoxin.model.domain.UserInfo;
import com.xiaoxin.model.enums.CommentType;
import com.xiaoxin.model.mongo.Comment;
import com.xiaoxin.model.vo.CommentVo;
import com.xiaoxin.model.vo.ErrorResult;
import com.xiaoxin.model.vo.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xiaoxiaode
 * @date 2021-09-05-22:50
 **/
@Service
@Slf4j
@SuppressWarnings("all")
public class CommentService {

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /*
     * 发布评论
     * */
    public void publishComments(String movementId, String comment) {
        Long id = UserHolder.getId();
        // 构造comment
        Comment comment1 = new Comment();
        comment1.setPublishId(new ObjectId(movementId));
        comment1.setCommentType(CommentType.COMMENT.getType());
        comment1.setContent(comment);
        comment1.setUserId(id);
        comment1.setCreated(System.currentTimeMillis());
        Integer commentCount = commentApi.save(comment1);
        // log.info(commentCount+"");
    }

    /*
     * 查询评论列表
     * */
    public PageResult findComments(Integer page, Integer pagesize, String movementId) {
        List<Comment> comments = commentApi.findComments(page, pagesize, CommentType.COMMENT, movementId);
        // 判断集合是否存在
        if (CollUtil.isEmpty(comments)) {
            return new PageResult();
        }
        // 提取用户id,查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(comments, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        // 构造vo
        List<CommentVo> list = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo = map.get(comment.getUserId());
            if (userInfo != null) {
                CommentVo vo = CommentVo.init(userInfo, comment);
                String key = Constants.COMMENTS_INTERACT_KEY + comment.getPublishId().toString();
                String hashKey = Constants.COMMENTS_LIKE_HASHKEY + UserHolder.getId().toString();
                if (redisTemplate.opsForHash().hasKey(key, hashKey)) {
                    vo.setHasLiked(1);
                }
                list.add(vo);
            }
        }
        // 构造返回值
        return new PageResult(page, pagesize, 0L, list);
    }

    /*
     * 动态点赞
     * */
    public Integer like(String movementId) {
        // 调用api查询用户是否已点赞
        boolean boo = commentApi.hasComment(movementId, UserHolder.getId(), CommentType.LIKE);
        if (boo) {
            throw new BusinessException(ErrorResult.likeError());
        }
        // 保存数据到mongoDb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getId());
        comment.setCreated(System.currentTimeMillis());
        Integer likeCount = commentApi.save(comment);
        // 拼接redis的key,将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId.toString();
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getId().toString();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return likeCount;
    }

    /*
     * 取消点赞
     * */
    public Integer dislike(String movementId) {
        // 调用api查询用户是否已点赞
        boolean boo = commentApi.hasComment(movementId, UserHolder.getId(), CommentType.LIKE);
        // 没有点赞抛出异常?
        if (!boo) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        // 保存数据到mongoDb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getId());
        Integer likeCount = commentApi.remove(comment);
        // 拼接redis的key,删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId.toString();
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getId().toString();
        redisTemplate.opsForHash().delete(key, hashKey);
        return likeCount;
    }

    /*
     * 喜欢
     * */
    public Integer love(String movementId) {
        // 调用api查询用户是否已点赞
        boolean boo = commentApi.hasComment(movementId, UserHolder.getId(), CommentType.LOVE);
        if (boo) {
            throw new BusinessException(ErrorResult.loveError());
        }
        // 保存数据到mongoDb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getId());
        comment.setCreated(System.currentTimeMillis());
        Integer likeCount = commentApi.save(comment);
        // 拼接redis的key,将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId.toString();
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getId().toString();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return likeCount;
    }

    /*
     * 取消喜欢
     * */
    public Integer unlove(String movementId) {
        // 调用api查询用户是否已点赞
        boolean boo = commentApi.hasComment(movementId, UserHolder.getId(), CommentType.LOVE);
        // 没有点赞抛出异常?
        if (!boo) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        // 保存数据到mongoDb
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(CommentType.LOVE.getType());
        comment.setUserId(UserHolder.getId());
        Integer likeCount = commentApi.remove(comment);
        // 拼接redis的key,删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId.toString();
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getId().toString();
        redisTemplate.opsForHash().delete(key, hashKey);
        return likeCount;
    }

    /*
     * 评论点赞
     * */
    public Integer likeComment(ObjectId publishId) {
        // 查询是否已喜欢
        Boolean boo = commentApi.hasComment(publishId.toString(), UserHolder.getId(), CommentType.LIKE);
        if (boo) {
            throw new BusinessException(ErrorResult.likeError());
        }
        // 保存数据到mongoDb
        Comment comment = new Comment();
        comment.setPublishId(publishId);
        comment.setCommentType(CommentType.LIKE.getType());
        comment.setUserId(UserHolder.getId());
        comment.setCreated(System.currentTimeMillis());
        Integer likeCount = commentApi.saveComment(comment, publishId);
        // 拼接redis的key,将用户的点赞状态存入redis
        String key = Constants.COMMENTS_INTERACT_KEY + publishId.toString();
        String hashKey = Constants.COMMENTS_LIKE_HASHKEY + UserHolder.getId().toString();
        redisTemplate.opsForHash().put(key, hashKey, "xy");
        return likeCount;
    }

    /*
     * 取消评论点赞
     * */
    public Integer dislikeComment(ObjectId publishId) {
        Boolean boo = commentApi.hasComment(publishId.toString(), UserHolder.getId(), CommentType.LIKE);
        if (!boo) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        Comment comment = new Comment();
        comment.setPublishId(publishId);
        comment.setUserId(UserHolder.getId());
        comment.setCreated(System.currentTimeMillis());
        comment.setCommentType(CommentType.LIKE.getType());
        Integer likeCount = commentApi.delete(comment);
        // 拼接redis的key,删除点赞状态
        String key = Constants.COMMENTS_INTERACT_KEY + publishId.toString();
        String hashKey = Constants.COMMENTS_LIKE_HASHKEY + UserHolder.getId().toString();
        redisTemplate.opsForHash().delete(key, hashKey);
        return likeCount;
    }

}
